package com.shanzhu.flower.controller;

import com.shanzhu.flower.entity.Purchase;
import com.shanzhu.flower.entity.R;
import com.shanzhu.flower.service.PurchaseService;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/purchase")
public class PurchaseController {
    @Resource
    private PurchaseService purchaseService;

    @GetMapping("/list")
    public R list(@RequestParam(defaultValue = "1") int page,
                  @RequestParam(defaultValue = "10") int pageSize,
                  @RequestParam(defaultValue = "") String searchKey) {
        int offset = (page - 1) * pageSize;
        List<Purchase> list = purchaseService.findPage(searchKey, offset, pageSize);
        int total = purchaseService.count(searchKey);
        java.util.Map<String, Object> map = new java.util.HashMap<>();
        map.put("items", list);
        map.put("total", total);
        return new R().setCode(2000).setData(map);
    }

    @PostMapping("/create")
    public R create(@RequestBody Purchase purchase) {
        purchase.setTotal(purchase.getQuantity() * purchase.getPrice());
        int res = purchaseService.add(purchase);
        return res == 1 ? new R().setCode(2000).setMsg("添加成功") : new R().setCode(4000).setMsg("添加失败");
    }

    @PutMapping("/update")
    public R update(@RequestBody Purchase purchase) {
        purchase.setTotal(purchase.getQuantity() * purchase.getPrice());
        int res = purchaseService.update(purchase);
        return res == 1 ? new R().setCode(2000).setMsg("修改成功") : new R().setCode(4000).setMsg("修改失败");
    }

    @DeleteMapping("/delete")
    public R delete(@RequestParam("id") int id) {
        int res = purchaseService.delete(id);
        return res == 1 ? new R().setCode(2000).setMsg("删除成功") : new R().setCode(4000).setMsg("删除失败");
    }
} 